﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using SQLHelper;

public partial class account_Register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // 首先检查保存用户邮箱和密码的cookie是否存在，存在登录，不存在跳回登录页
        if (Request.Cookies["NOAP_USER_ACCOUNT"] != null)
        {
            HttpCookie UserAccountCookie = Request.Cookies["NOAP_USER_ACCOUNT"];
            string email = Convert.ToString(UserAccountCookie.Values["NOAP_USER_ACCOUNT_EMAIL"]);
            string password = Convert.ToString(UserAccountCookie.Values["NOAP_USER_ACCOUNT_PASSWORD"]);
            Session["email"] = email;
            Session["password"] = password;
            Response.Redirect("~/admin/Default.aspx");
        }

        // 有session,跳回主页
        if (Session["email"] != null && Session["password"] != null)
        {
            Response.Redirect("~/admin/Default.aspx");
        }
    }

    protected void register(object sender, EventArgs e)
    {
        string name = TextBox1.Text;
        string email = TextBox2.Text;
        string password = TextBox3.Text;
        string check = TextBox5.Text;

        if(check == "on")
        {
            string md5Password = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
            // 加密密码
            string checkSql = "select * from users where email = '" + email + "'";
            SqlDataReader res = DB.GetDataWithQuery(checkSql);
            // 检查是否存在
            if (res.Read())
            {
                DB.ColseSqlCon();
                Label1.Text = "此邮箱已经被注册过了！";
            }
            else
            {
                DB.ColseSqlCon();
                string sql = "insert into users (name, email, password, created_at) values ('" + name + "','" + email + "', '" + md5Password + "','" + DateTime.Now + "')";
                DB.GetDataNoQuery(sql);
                DB.ColseSqlCon();
                // 写入用户注册信息
                string roleSql = "INSERT INTO role_user (user_id) SELECT id FROM users where email = '" + email + "'";
                DB.GetDataNoQuery(roleSql);
                DB.ColseSqlCon();
                // 写入用户角色
                Label3.Text = "注册成功即将跳转";
                // 创建用户
                Session["email"] = email;
                Session["password"] = md5Password;
                Response.Redirect("~/admin/Default.aspx");
                // 自动登录，进入后台
            }
        }
        else
        {
            Label2.Text = "不确认是无法注册的哦~";
        }
    }
}